<?php
namespace app\admin\controller;

use app\common\controller\Base;
use think\Request;
use think\Session;
use app\common\service\Fileware as FilewareService;

class Upload extends Base{

    public function upload(){
        //将上传的图片保存到数据库当中 知道哪个用户上传了那张图 还可以达到复用的目的
        // 获取表单上传文件 例如上传了001.jpg
        $originName = $_FILES['file']['name'];

        $file = request()->file('file');

        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
        if($info){

            $store = [];
            $store['filename']=$info->getFilename();
            $store['ext'] = $info->getExtension();
            $store['size'] = $info->getSize();
            $store['originname'] = $originName;
            $store['url'] = '/uploads/'.$info->getSaveName();
            $this->save($store);

            $return = [];
            $return['code'] = 1;
            $return['msg'] = "上传成功";
            $return['data'] = [];
            $return['data']['src'] = $store['url'];

        }else{
            // 上传失败获取错误信息
            $return = [];
            $return['code'] = 1;
            $return['msg'] = $file->getError();
            $return['data'] = [];
        }

        return json_encode($return);
    }

    /**
     * 保存在数据库中
     * @param $store
     * @return false|int
     */
    private function save($store){
        $user = Session::get(config("sessionKey.loginUserKey"));
        $store['userid'] = $user->id;
        $filewareService = new FilewareService();
        $id = $filewareService->insert($store);
        return $id;
    }

}